package cn.comtom.ewbs.signature.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.comtom.ewbs.signature.common.vo.request.PageRequest;
import cn.comtom.ewbs.signature.entity.SignDev;
import cn.comtom.ewbs.signature.mapper.SignDevMapper;
import cn.comtom.ewbs.signature.service.ISignDevService;
import cn.comtom.ewbs.signature.service.ISignatureService;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuhy
 * @since 2022-11-07 11:21:28
 */
@Service
@Slf4j
public class SignDevServiceImpl extends ServiceImpl<SignDevMapper, SignDev> implements ISignDevService {
	
    @Autowired
    private ISignatureService signatureService;
	
	@Override
	public IPage<SignDev> selectPage(SignDev signDev, PageRequest pageReq) {
		Page<SignDev> page = new Page<SignDev>(pageReq.getPage() , pageReq.getLimit() , true);
        LambdaQueryWrapper<SignDev> wrapper = Wrappers.lambdaQuery();
        if(StrUtil.isNotBlank(signDev.getDevName())) {
        	wrapper.like(SignDev::getDevName, signDev.getDevName());	
        }
        return this.baseMapper.selectPage(page, wrapper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateEnable(SignDev sd) {
		SignDev sddb = this.getById(sd.getId());
		if(sddb == null) {
			return false;
		}
		if(sd.getDevStatus() == 0) {
    		//其中一个启用，禁用其他的
    		boolean update = this.lambdaUpdate().set(SignDev::getDevStatus, 1).update();
    		if(update) {
    			if(this.saveOrUpdate(sd)) {
    				return signatureService.initSignDev(sddb.getDevName());
    			}
    		}
    	}else {
    		return this.saveOrUpdate(sd);
    	}
		return false;
	}
}
